<template>
  <div class="min-h-screen flex items-center justify-center relative">
    <div class="aurora-background">
    </div>
    <div class="w-full max-w-md relative z-10">
      <!-- 登录卡片 -->
      <div class="bg-white rounded-2xl shadow-2xl p-8 mx-4">
        <!-- Logo 和标题 -->
        <div class="text-center mb-8">
          <div class="flex justify-center mb-4">
            <img src="/logo.svg" alt="CodeWin" class="w-16 h-16" />
          </div>
          <h1 class="text-2xl font-bold text-gray-800 mb-2">CodeWin</h1>
          <p class="text-gray-500 text-sm">登录您的账户</p>
        </div>

        <!-- 登录方式切换 -->
        <div class="mb-6 flex justify-center">
          <div class="login-type-switcher">
            <div
              v-for="option in loginOptions"
              :key="option.value"
              :class="[
                'login-type-option',
                { 'active': loginType === option.value }
              ]"
              @click="loginType = option.value as 'password' | 'email'"
            >
              {{ option.label }}
              <div class="underline-indicator"></div>
            </div>
          </div>
        </div>

        <!-- 登录表单 -->
        <form @submit.prevent="handleLogin" class="space-y-6">
          <!-- 账号密码登录 -->
          <template v-if="loginType === 'password'">
            <!-- 用户名输入 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                用户名
              </label>
              <a-input
                v-model:value="passwordForm.username"
                placeholder="请输入您的用户名"
                size="large"
                class="w-full"
              >
                <template #prefix>
                  <User :size="16" />
                </template>
              </a-input>
            </div>

            <!-- 密码输入 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                密码
              </label>
              <a-input-password
                v-model:value="passwordForm.password"
                placeholder="请输入您的密码"
                size="large"
                class="w-full"
              >
                <template #prefix>
                  <Lock :size="16" />
                </template>
              </a-input-password>
            </div>

            <!-- 记住我和忘记密码 -->
            <div class="flex items-center justify-between">
              <a-checkbox v-model:checked="passwordForm.remember">
                记住我
              </a-checkbox>
              <router-link to="/forgot" class="text-sm text-violet-600 hover:text-violet-500">
                忘记密码？
              </router-link>
            </div>
          </template>

          <!-- 邮箱验证码登录 -->
          <template v-else>
            <!-- 邮箱输入 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                邮箱
              </label>
              <a-input
                v-model:value="emailForm.email"
                type="email"
                placeholder="请输入您的邮箱"
                size="large"
                class="w-full"
              >
                <template #prefix>
                  <Mail :size="16" />
                </template>
              </a-input>
            </div>

            <!-- 验证码输入 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                邮箱验证码
              </label>
              <div class="flex space-x-2">
                <a-input
                  v-model:value="emailForm.code"
                  placeholder="请输入验证码"
                  size="large"
                  class="flex-1"
                >
                  <template #prefix>
                    <Shield :size="16" />
                  </template>
                </a-input>
                <a-button
                  size="large"
                  :loading="sendingCode"
                  :disabled="!emailForm.email || countdown > 0"
                  @click="sendVerificationCode"
                  class="px-4"
                >
                  {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
                </a-button>
              </div>
            </div>
          </template>

          <!-- 登录按钮 -->
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            class="w-full h-12 text-base font-medium bg-gradient-to-r from-violet-500 to-purple-600 border-none hover:from-violet-600 hover:to-purple-700"
          >
            登录
          </a-button>
        </form>

        <!-- 分割线 -->
        <div class="mt-6 mb-6">
          <div class="relative">
            <div class="absolute inset-0 flex items-center">
              <div class="w-full border-t border-gray-300"></div>
            </div>
            <!-- <div class="relative flex justify-center text-sm">
              <span class="px-2 bg-white text-gray-500">或者</span>
            </div> -->
          </div>
        </div>

        <!-- 第三方登录图标 -->
        <!-- <div class="flex justify-center space-x-6">
          <div class="cursor-pointer hover:opacity-70 transition-opacity">
            <Github class="w-6 h-6 text-gray-600" />
          </div>
          <div class="cursor-pointer hover:opacity-70 transition-opacity">
            <Chrome class="w-6 h-6 text-gray-600" />
          </div>
          <div class="cursor-pointer hover:opacity-70 transition-opacity">
            <Twitter class="w-6 h-6 text-gray-600" />
          </div>
          <div class="cursor-pointer hover:opacity-70 transition-opacity">
            <Facebook class="w-6 h-6 text-gray-600" />
          </div>
        </div> -->

        <!-- 注册链接 -->
        <div class="mt-6 text-center">
          <span class="text-sm text-gray-600">
            还没有账户？
            <router-link to="/register" class="font-medium text-violet-600 hover:text-violet-500">
              立即注册
            </router-link>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { Mail, Lock, User, Shield } from 'lucide-vue-next'
import { Codewin } from '@/api/generated/Codewin'
import type { LoginRequest, EmailLoginRequest } from '@/api/generated/data-contracts'
import { useAuthStore, useUserStore } from '@/stores'

const router = useRouter()
const authStore = useAuthStore()
const userStore = useUserStore()
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)

// 登录方式
const loginType = ref<'password' | 'email'>('password')
const loginOptions = [
  { label: '账号密码', value: 'password' },
  { label: '邮箱验证码', value: 'email' }
]

// 创建API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
})

// 账号密码登录表单
const passwordForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 邮箱验证码登录表单
const emailForm = reactive({
  email: '',
  code: ''
})

// 发送验证码
const sendVerificationCode = async () => {
  if (!emailForm.email) {
    message.error('请先输入邮箱地址')
    return
  }

  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(emailForm.email)) {
    message.error('请输入正确的邮箱格式')
    return
  }

  sendingCode.value = true
  
  try {
    await api.sendCode({ email: emailForm.email })
    message.success('验证码已发送到您的邮箱')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    message.error(error?.response?.data?.message || '发送验证码失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 处理登录
const handleLogin = async () => {
  loading.value = true
  try {
    let response
    
    if (loginType.value === 'password') {
      // 账号密码登录
      const loginData: LoginRequest = {
        username: passwordForm.username,
        password: passwordForm.password
      }
      response = await api.login(loginData)
    } else {
      // 邮箱验证码登录
      const emailLoginData: EmailLoginRequest = {
        email: emailForm.email,
        code: emailForm.code
      }
      response = await api.loginByEmail(emailLoginData)
    }

    if (response.data.code === 0) {
      message.success('登录成功！')
      
      // 存储token到状态管理
      authStore.setToken(response.data.data)
      
      // 立即获取用户信息
      await userStore.fetchUserInfo()
      
      // 跳转到首页
      router.push('/')
    } else {
      message.error(response.data.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    message.error(error.response?.data?.message || '登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 自定义样式 */
.ant-input-affix-wrapper {
  border-radius: 8px;
}

.ant-btn {
  border-radius: 8px;
}

/* 登录方式切换器样式 */
.login-type-switcher {
  display: flex;
  gap: 2rem;
  position: relative;
}

.login-type-option {
  padding: 0.75rem 1rem;
  cursor: pointer;
  color: #9ca3af;
  font-weight: 500;
  transition: all 0.3s ease;
  user-select: none;
  position: relative;
  background: transparent;
  border: none;
}

.login-type-option:hover {
  color: #6366f1;
}

.login-type-option.active {
  color: #6366f1;
}

.underline-indicator {
  position: absolute;
  bottom: -2px;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #6366f1, #8b5cf6);
  border-radius: 1px;
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.login-type-option.active .underline-indicator {
  transform: scaleX(1);
}
</style>